package org.niu.dp;

public class LCS {
    public String LCS (String str1, String str2) {
        // write code here
        int n = str1.length(),m = str2.length();
        String[][] dp = new String[n+1][m+1];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                dp[i][j] = "";
            }
        }
        int flag = 0;
        for(int i = 0;i < n;i++){
            if(flag == 1) {dp[i][0] += str2.charAt(0);continue;}
            if(str1.charAt(i) == str2.charAt(0)){
                flag = 1;
            }
        }
        flag = 0;
        for(int i = 0;i < m;i++){
            if(flag == 1) {dp[0][i] += str1.charAt(0);continue;}
            if(str2.charAt(i) == str1.charAt(0)){
                flag = 1;
            }
        }


        String ans = "";
        for(int i = 1;i < n;i++){
            for (int j = 1; j < m; j++) {
                if(dp[i-1][j].equals(dp[i][j-1])){
                    if(str1.charAt(i) == str2.charAt(j)){
                        dp[i][j] += str1.charAt(i);
                        if(dp[i][j].length() > ans.length()){
                            ans = dp[i][j];
                        }
                    }
                }else{
                    dp[i][j] = dp[i-1][j].length() > dp[i][j-1].length() ? dp[i-1][j]:dp[i][j-1];
                }
            }
        }
        return ans;
    }
}
